const { objMod } = require('../models');
const nunjucks = require('nunjucks');


let uName, pwd;

let res = {

    // 登录提交
    "/doLogin": ["post", async (ctx) => {

        //获取当前表单的username和password的值
        uName = ctx.request.body.username;
        pwd = ctx.request.body.password;

        //查询Users表
        let articles = await objMod.Users.findAll({
            attributes: ["id", "username", "password"]
        });

        console.log("用户数量" + articles.length);


        //获取数据库中的用户名和密码
        for (let i = 0; i < articles.length; i++) {

            //使用trim()方法去除数据库中账号和密码头尾的空格
            let nameForDatabase = articles[i].username.trim();
            let pwdForDatabase = articles[i].password.trim();

            //获取当前用户的id
            let idForDatabase = articles[i].id;

            // console.log("当前用户id：" + idForDatabase);
            // console.log("数据账号：" + nameForDatabase);
            // console.log("数据库密码：" + pwdForDatabase);

            //如果登录成功
            if (uName === nameForDatabase && pwd === pwdForDatabase) {

                //跳转路由
                ctx.redirect("/index")

                //设置session
                ctx.session.username = uName;
                ctx.session.userId = idForDatabase;

            } else {
                // console.log(uName);
                // console.log(pwd);

                //跳到初始登录界面          
                ctx.body = await nunjucks.renderString(`
            <script type="text/javascript">
            alert("登录失败,请检查账号或密码是否错误");
            window.location.href = "/";//跳转后的页面
         </script>
           `);

            }

        }
    },
    ],
};

module.exports = res;
